﻿/**************
Usage :
timer.start(_sec);
timer.resume();
timer.pause();
timer.stop();
timer.reset();

// will dispatch TimeEvent START,PAUSE,RESUME,STOP,RUNNING,FINISH
//************/
package com.cf.core.control{
	import flash.utils.Timer;
	import flash.events.TimerEvent;
	import flash.events.EventDispatcher;
	import com.cf.core.events.TimeEvent;
	public class MyTimer extends EventDispatcher{
		private const DELAY:uint=1000;	// 1 second
		
		private var G_time:Timer;
		private var G_timeLeft:Number;
		public function get timeLeft():Number{return ((DELAY * G_timeLeft) / 1000)}
		
		private var G_idle:Boolean;
		public function get idle():Boolean{return G_idle}
		public function MyTimer():void{
			G_idle=true;
		}
		
		public function start(_sec:uint=0):void{
			G_timeLeft=_sec;
			G_time = new Timer(DELAY, G_timeLeft);
			G_idle=false;
			G_time.addEventListener(TimerEvent.TIMER, timerHandler);
            G_time.addEventListener(TimerEvent.TIMER_COMPLETE, completeHandler);
			G_time.start();
			dispatchEvent(new TimeEvent(TimeEvent.START));
		}//fn
		public function resume():void{
			try{
				G_time.start();
				G_idle=false;
				dispatchEvent(new TimeEvent(TimeEvent.RESUME));
			}catch(e){}
		}//fn
		public function pause():void{
			try{
				G_time.stop();
				G_idle=true;
				dispatchEvent(new TimeEvent(TimeEvent.PAUSE));
			}catch(e){}
		}//fn
		public function stop():void{
			try{
				G_time.removeEventListener(TimerEvent.TIMER, timerHandler);
	            G_time.removeEventListener(TimerEvent.TIMER_COMPLETE, completeHandler);
				G_time.stop();
				G_time.reset();
				G_idle=true;
				G_timeLeft=0;
				dispatchEvent(new TimeEvent(TimeEvent.STOP));
			}catch(e){}
		}//fn
		
		private function timerHandler(e:TimerEvent):void{
			G_timeLeft--;
			// trace( timeLeft+ " seconds left.");
			dispatchEvent(new TimeEvent(TimeEvent.RUNNING));
        }//fn
        private function completeHandler(e:TimerEvent):void {
			G_time.reset();
			G_idle=true;
			// trace("MyTimer : Times up.");
			dispatchEvent(new TimeEvent(TimeEvent.FINISH));
		}//fn
		
		public function reset():void{
			stop();
			try{
				G_time.addEventListener(TimerEvent.TIMER, timerHandler);
    	        G_time.addEventListener(TimerEvent.TIMER_COMPLETE, completeHandler);
			}catch(e){}
		}//fn
	}//class
}//package